package com.education.realtime.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.education.realtime.common.Constant;
import redis.clients.jedis.Jedis;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class DimUtil {
    public static JSONObject getDimFromPhoenix(Connection phoenixConn, String tableName, String id) {
        String sql = "select * from " + tableName + " where id=?";// TODO
        Object[] args = {id};
        // 通过jdbc查找phoenix数据库
        List<JSONObject> result;
        try {
            result = JDBCUtil.queryList(phoenixConn, sql, args, JSONObject.class);
        } catch (SQLException e) {
            throw new RuntimeException("sql语句有问题, 请检查sql语句 ");
        }catch (IllegalAccessException | InstantiationException e) {
            throw new RuntimeException(" 提供的泛型类型没有无参构造器或者无参构造器私有了... ");
        } catch (InvocationTargetException e) {
            throw new RuntimeException(" 属性名和数据库中的字段名不一致 ");
        }
    
        if (result.size() == 0) {
            throw new RuntimeException("没有查到对应的维度信息, 表名:" + tableName + ", id:" + id);
        }
        return result.get(0);
    }
    
    public static JSONObject getDim(Jedis redisClient, Connection phoenixConn, String tableName, String id) {
        // 1. 先从redis读取维度
       JSONObject dim =  getDimFromRedis(redisClient,tableName ,id);
        // 2. 如果返回值是null, 表示redis不存在. 从phoenix读取. 再把读到的维度写入到redis
        if (dim == null) {
            System.out.println("走的数据库:" + tableName + "  " + id);
            dim = getDimFromPhoenix(phoenixConn, tableName, id);
            writeDimToRedis(redisClient, tableName, id, dim);
        }else{
            System.out.println("走的缓存:" + tableName + "  " + id);
        }
        // 3. 如果存在则直接返回
        return dim;
    }
    
    
    // TODO
    private static void writeDimToRedis(Jedis redisClient,
                                        String tableName,
                                        String id,
                                        JSONObject dim) {
        
        String key = tableName + ":" + id;
        String value = dim.toJSONString();
    
        /*redisClient.set(key, value);
        redisClient.expire(key, Constant.DIM_TTL);
        */
        redisClient.setex(key, Constant.DIM_TTL, value);
    }
    
    // TODO
    private static JSONObject getDimFromRedis(Jedis redisClient,
                                              String tableName,
                                              String id) {
        String key = tableName + ":" + id;
        String dimJsonString = redisClient.get(key);
        
        JSONObject dim = null;
        if (dimJsonString != null) {
            dim = JSON.parseObject(dimJsonString);
        }
    
        return dim;
    }
}